package cn.kgc.shiroday03.shiro;

import cn.kgc.shiroday03.entity.Permission;
import cn.kgc.shiroday03.entity.RolePers;
import cn.kgc.shiroday03.entity.User;
import cn.kgc.shiroday03.entity.UserRole;
import cn.kgc.shiroday03.mapper.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/6/3
 * @Description:
 */
public class CustomerRealm  extends AuthorizingRealm {

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RolePersMapper rolePersMapper;

    @Resource
    private PermissionMapper permissionMapper;

    //  该方法 在用户访问受限资源时  被自动调用
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("================授权的方法被调用==================");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 根据用户的身份信息  primaryPrincipal  用户名  查询用户角色信息  RBAC     user  user_role   role
        String primaryPrincipal =(String) principals.getPrimaryPrincipal();
        // 查询数据库
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername,primaryPrincipal);
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        Integer userId = user.getId();

        // 2. 根据用户id  查询用户角色id   user_role
        LambdaQueryWrapper<UserRole> lambda = new QueryWrapper<UserRole>().lambda();
        lambda.eq(UserRole::getUserId,userId);
        List<UserRole> userRoles = userRoleMapper.selectList(lambda);
        List<Integer> rids = userRoles.stream().map(ur -> ur.getRoleId()).collect(Collectors.toList());

        // 3.根据角色id 查询用户角色名称  role
        List<String> roleNames = roleMapper.selectBatchIds(rids).stream().map(role -> role.getRoleName()).collect(Collectors.toList());
        System.out.println("roleNames = " + roleNames);
        simpleAuthorizationInfo.addRoles(roleNames);

        // 3. 查询用户拥有的权限字符串   rids    role_permission   pid   -> permission表   ->permission 权限字符串

        LambdaQueryWrapper<RolePers> lambda1 = new QueryWrapper<RolePers>().lambda();
        lambda1.in(RolePers::getRoleId,rids);

        List<Integer> pids = rolePersMapper.selectList(lambda1).stream().map(rp -> rp.getPerId()).collect(Collectors.toList());

        List<Permission> permissions = permissionMapper.selectBatchIds(pids);
        List<String> strPermissions = permissions.stream().map(p -> p.getPermission()).filter(p -> p!= null).collect(Collectors.toList());

        simpleAuthorizationInfo.addStringPermissions(strPermissions);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        System.out.println("================认证的方法被调用==================");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();
        // 查询数据库
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername,username);
        User user = userMapper.selectOne(userLambdaQueryWrapper);

        if(!ObjectUtils.isEmpty(user)){
            // 判定用户的状态
            if(user.getState()==0){
                throw  new  LockedAccountException();
            }
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
            return  simpleAuthenticationInfo;
        }

        return null;
    }
}
